package net.area80.image
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import net.area80.utils.LoaderUtils;
	
	public class ImageBox extends Sprite
	{
		private var fillBox:Boolean;
		private var path:String;
		private var w:uint;
		private var h:uint;
		private var ldr:Loader;
		private var src:Bitmap;
		
		public function ImageBox(src:*,boxw:uint,boxh:uint,fillBox:Boolean=true)
		{
			super();
			w = boxw;
			h = boxh;
		
			this.fillBox = fillBox;
			addEventListener(Event.REMOVED_FROM_STAGE, dispose);
			if(src is String) {
				this.path = src;
				initLoader();
			} else if (src is BitmapData) {
				this.src = new Bitmap(src,"auto",true);
				addChild(this.src);
				resizeToFitBox();
			}
			
		}
		private function initLoader ():void {
			
			
			ldr = new Loader();
			ldr.load(new URLRequest(path));
			ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComp);
			ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
		}
		private function loadError (e:Event):void {
			initLoader();
		}
		public override function get width ():Number {
			return (fillBox || !src) ? w : src.width;
		}
		public override function set width (w:Number):void {
			this.w = w;
			resizeToFitBox();
		}
		public override function get height ():Number {
			return (fillBox || !src) ? h : src.height;
		}
		public override function set height (h:Number):void {
			this.h = h;
			resizeToFitBox();
		}
		private function resizeToFitBox ():void {
			//trace("available height:"+h);
			if(src){
				src.scaleX = src.scaleY = 1;
				var sx:Number = w/src.width;
				var sy:Number = h/src.height;
				var scale:Number = Math.min(sx,sy);
				if(!fillBox && scale >1) scale =1;
				src.scaleX = src.scaleY = scale;
				if(fillBox) {
					src.x = (w-src.width)*0.5;
					src.y = (h-src.height)*0.5;
				} else {
					src.x = 0;
					src.y = 0;
				}
			}
		}
		private function loadComp(e:Event):void {
			try {
				Bitmap(ldr.content).smoothing = true;
			} catch (e:Error){}
			src = ldr.content as Bitmap;
			addChild(src);
			resizeToFitBox();
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function dispose (e:Event=null):void {
			if(ldr) LoaderUtils.clearLoader(ldr);
		}
	}
}